package com.oc.claimobs.bb.dao;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import ar.com.lemil.j2me.serialization.ObjectInputStream;
import ar.com.lemil.j2me.serialization.ObjectOutputSream;

import com.oc.claimobs.bb.facade.Persistance;

public class FileDao implements Persistance {

	private static final String extension = "inf";

	private String root;

	public FileDao(String rootPath) {
		root = rootPath;
	}

	public void saveOrUpdate(Object key, Object o) {
		FileConnection file = null;
		ObjectOutputSream out = null;
		OutputStream out2 = null;
		try {
			String fname = root + key + "." + extension;
			file = (FileConnection) Connector.open(fname);

			if (file.exists()) {
				file.delete();
			}
			file.create();

			// Serialize Object
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			out = new ObjectOutputSream(baos);
			out.writeObject(o);
			out.flush();

			// Persist serialization
			out2 = file.openDataOutputStream();
			out2.write(baos.toByteArray());
		} catch (Exception ex) {
			throw new RuntimeException(ex.toString() + ":" + ex.getMessage());
		} finally {
			try {
				out.close();
			} catch (Exception ex) {
			}
			try {
				out2.close();
			} catch (Exception ex) {
			}
			try {
				file.close();
			} catch (Exception ex) {
			}
		}
	}
	
	public Object getByKey(Object key) {
	
		FileConnection file = null;
		ObjectInputStream in = null;
		InputStream in2 = null;
		try {
			String fname = root + key.toString() + "." + extension;
			file = (FileConnection) Connector.open(fname);

			if (!file.exists()) {
				return null;
			}

			// un  Persist serialization
			in2 = file.openInputStream();
			// un Serialize Object
			in = new ObjectInputStream(in2);
			final Object o = in.readObject();
			
			return o;

		} catch (Exception ex) {
			throw new RuntimeException(ex.toString() + ":" + ex.getMessage());
		} finally {
			try {
				in.close();
			} catch (Exception ex) {
			}
			try {
				in2.close();
			} catch (Exception ex) {
			}
			try {
				file.close();
			} catch (Exception ex) {
			}
		}
	}

	public void delete(Object key) {
		try {
			FileConnection file = (FileConnection) Connector.open(key + "." + extension);

			if (file.exists()) {
				file.delete();
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex.toString() + ":" + ex.getMessage());
		}

	}





}
